<template>
  <div class="vote-apply">
    <div style="height: 5px;"></div>
    <div class="vote-apply-title">
      <router-link :to="'/wx/i/votes-'+$route.params.id" tag="div" replace class="title-left">
        <div class="title-icon">
          <i class="van-icon van-icon-arrow-left"></i>
        </div>
        <div class="title-left-cont">
          返回
        </div>
      </router-link>
      报名
    </div>
    <div class="vote-apply-cont">
      <div v-if="check === 0">
        <FormBlock title="名称">
          <cell-group>
            <Field v-model="apply.name" placeholder="请输入姓名或商户名称"/>
          </cell-group>
        </FormBlock>
        <FormBlock title="联系方式">
          <cell-group>
            <Field v-model="apply.phone" placeholder="请输入手机号"/>
          </cell-group>
        </FormBlock>

        <FormBlock title="介绍">
          <cell-group>
            <field v-model="apply.introduce" type="textarea" placeholder="请输入介绍" rows="3" autosize/>
          </cell-group>
        </FormBlock>

        <FormBlock title="封面图片">
          <div style="min-height: 44px;padding: 15px;background-color: #FFF;">
            <div v-if="apply.cover != ''" class="apply-img-out">
              <i @click="coverDel" class="van-icon van-icon-close apply-icon-del"></i>
              <img :src="'https://img.sdwsl.net/'+apply.cover" style="height: auto;width: 50%;"/>
            </div>
            <wxUploadImg v-show="apply.cover == ''" :sizeType="['compressed']" @upload="coverUpload">
              <template slot="picker">
                <div style="padding-top: 10px;">
                  <div class="picker-button">上传封面</div>
                </div>
              </template>
            </wxUploadImg>
            <!--<VueQiniuUpload v-show="apply.cover == ''" :token="imgToken" @upload="coverUpload">-->
            <!--<template slot="form">-->
            <!--<input name="key" type="hidden" :value="applyCoverKey">-->
            <!--</template>-->
            <!--<template slot="picker">-->
            <!--<div style="padding-top: 10px;">-->
            <!--<div class="picker-button">上传封面</div>-->
            <!--</div>-->
            <!--</template>-->
            <!--</VueQiniuUpload>-->
          </div>
        </FormBlock>

        <FormBlock title="介绍图片">
          <div style="min-height: 44px;padding: 15px;background-color: #FFF;">
            <div v-for="(img, i) in apply.imgs" class="apply-img-out">
              <i @click="applyContDel(i)" class="van-icon van-icon-close apply-icon-del"></i>
              <img :src="'https://img.sdwsl.net/'+img" style="height: auto;width: 100%;"/>
            </div>
            <wxUploadImg v-show="apply.imgs.length < 6" :count="6-apply.imgs.length" :sizeType="['compressed']" @upload="contUpload">
              <template slot="picker">
                <div style="padding-top: 10px;">
                  <div class="picker-button">上传图片</div>
                </div>
              </template>
            </wxUploadImg>
          </div>
        </FormBlock>

        <div style="padding: 15px;">
          <Button type="primary" @click="submitApply" size="large">报名</Button>
        </div>
      </div>
      <div v-if="check === 1" style="text-align: center;padding-top: 40px;font-size: 20px;">
        您已经报名了!
      </div>
      <div v-if="check === 2" style="text-align: center;padding-top: 40px;font-size: 20px;">
        报名成功！
      </div>
    </div>
  </div>
</template>

<script>
  import {Icon, Tab, Tabs, Button, Search, Actionsheet, Panel, Popup, Waterfall, Swipe, SwipeItem, Field, Cell, CellGroup, Loading, Toast} from 'vant'
  import vueWaterfallEasy from 'components/vue-waterfall-easy.vue'
  import Scroll from 'base/scroll/scroll'
  import FormBlock from 'components/form-block'
  import VueQiniuUpload from 'components/vue-qiniu-upload'
  import QnBase64Upload from 'components/vue-qiniu-upload/Base64-upload'
  import wxUploadImg from 'components/wx/wx-upload-img'
  import * as api from '@/api/api'
  import initJSSDK from '@/js/wxJSSDK'
  import * as qiniu from '@/js/qiniu'

  export default {
    name: 'index',
    data () {
      return {
        check: 3,
        applyCoverKey: this.$route.params.id + '-cover-' + new Date().getTime(),
        // 封面
        cover: {},
        // 报名信息
        apply: {
          // 投票ID
          voteId: this.$route.params.id,
          name: '',
          introduce: '',
          phone: '',
          // 封面
          cover: '',
          imgs: []
        },
        clientWidth: 0,
        imgWidth: 0,
        imgToken: ''
      }
    },
    methods: {
      checkStatus () {
        api.post({
          url: '/vote/user/check',
          data: {voteId: this.$route.params.id},
          success: data => {
            this.check = data.code
          }
        })
      },
      verify () {
        let apply = this.apply
        if (apply.name === '') {
          Toast.fail('名称不能为空')
          return false
        } else if (apply.phone === '') {
          Toast.fail('手机不能为空')
          return false
        } else if (apply.phone.length !== 11) {
          Toast.fail('手机号码不正确')
          return false
        } else if (apply.introduce === '') {
          Toast.fail('介绍不能为空')
          return false
        } else if (apply.introduce.length < 30) {
          Toast.fail('介绍不能少于30字')
          return false
        } else if (apply.introduce.length > 800) {
          Toast.fail('介绍不能大于800字')
          return false
        } else if (apply.cover === '') {
          Toast.fail('封面不能为空')
          return false
        } else if (apply.imgs.length === 0) {
          Toast.fail('内容图片不能为空')
          return false
        }
        return true
      },
      submitApply () {
        let verify = this.verify()
        if (verify) {
          let applys = {}
          Object.assign(applys, this.apply)
          applys.imgs = applys.imgs.join(',')
          // console.log(JSON.stringify(applys))
          api.post({
            url: '/vote/user/add',
            data: applys,
            success: data => {
              if (data.code === 0) {
                this.check = 2
              }
            }
          })
        }
      },
      // 封面上传回调
      coverUpload (localIds) {
        Toast.loading({mask: true, duration: 0, forbidClick: true, message: '图片上传中'})
        this.$wx.getLocalImgData({
          localId: localIds[0], // 图片的localID
          success: res => {
            let localData = res.localData // localData是图片的base64数据，可以用img标签显示
            qiniu.postBase64Img(localData, this.imgToken, this.applyCoverKey, key => {
              this.apply.cover = key
              Toast.clear()
            })
          }
        })
      },
      // 封面删除
      coverDel (res) {
        this.apply.cover = ''
        this.applyCoverKey = this.$route.params.id + '-cover-' + new Date().getTime()
      },
      // 报名内容图片上传
      contUpload (localIds) {
        if (localIds.length > 0) {
          Toast.loading({mask: true, duration: 0, forbidClick: true, message: '图片上传中'})
          this.$wx.getLocalImgData({
            localId: localIds.shift(), // 图片的localID
            success: res => {
              let localData = res.localData // localData是图片的base64数据，可以用img标签显示
              qiniu.postBase64Img(localData, this.imgToken, this.$route.params.id + '-imgs-' + new Date().getTime(), key => {
                this.apply.imgs.push(key)
                this.contUpload(localIds)
              })
            }
          })
        } else {
          Toast.clear()
        }
      },
      applyContDel (index) {
        this.apply.imgs.splice(index, 1)
        // console.log(index)
        // console.log(this.apply.imgs[index])
        // get('/qn/delImage', {key: this.apply.imgs[index]}, data => {
        //   console.log(data)
        //   if (data.code === 0) {
        //     this.apply.imgs.splice(index, 1)
        //   }
        // })
      },
      handleTabClick () {
      },
      getImgToken () {
        api.get({
          url: '/qn/getImgToken',
          data: {},
          success: (data) => {
            this.imgToken = data.token
          }
        })
      },
      init () {
        this.getImgToken()
        // this.initJsSdk()
        initJSSDK(this)
      }
    },
    computed: {},
    created () {
    },
    mounted () {
      // console.log(this.$route.path)
      this.checkStatus()
      let clientWidth = document.body.clientWidth
      this.clientWidth = clientWidth
      this.imgWidth = (clientWidth - 30) / 2
      this.init()
    },
    watch: {},
    directives: {
      WaterfallLower: Waterfall('lower')
    },
    components: {wxUploadImg, QnBase64Upload, Icon, Tab, Tabs, Button, vueWaterfallEasy, Scroll, Search, Actionsheet, Panel, Popup, Waterfall, Swipe, SwipeItem, Field, Cell, CellGroup, FormBlock, Loading, VueQiniuUpload, Toast}
  }
</script>

<style lang="scss" scoped>
  // 报名
  .vote-apply {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100vh;
    width: 100vw;
    display: flex;
    flex-direction: column;
    background-color: #f8f8f8;
    &-title {
      height: 44px;
      line-height: 44px;
      border-bottom: 1px #ededed solid;
      text-align: center;
      font-size: 17px;
      position: relative;
      .title-left {
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        text-align: left;
        padding-left: 15px;
        min-width: 50px;
        .title-icon {
          display: inline-block;
          height: 44px;
          vertical-align: middle;
        }
        .title-left-cont {
          display: inline-block;
          height: 44px;
        }
      }
    }
    &-cont {
      flex: 1;
      overflow-y: auto;
      .apply-img-out {
        position: relative;
        .apply-icon-del {
          position: absolute;
          top: 10px;
          right: 10px;
          color: red !important;
          font-size: 35px;
        }
      }
    }
  }

  .vote-button {
    padding-left: 20px !important;
    padding-right: 20px !important;
  }

  // 封面上传按钮
  .picker-button {
    position: relative;
    padding: 0;
    display: inline-block;
    border-radius: 4px;
    box-sizing: border-box;
    text-align: center;
    -webkit-appearance: none;
    color: #fff;
    background-color: #4b0;
    border: 1px solid #0a0;
    min-width: 60px;
    height: 30px;
    line-height: 28px;
    font-size: 12px;
    padding-left: 20px !important;
    padding-right: 20px !important;
  }


</style>
